package com.example.demo;



import io.netty.bootstrap.ServerBootstrap;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.ChannelOption;
import io.netty.channel.EventLoopGroup;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioServerSocketChannel;
import io.netty.handler.codec.LengthFieldBasedFrameDecoder;
import io.netty.handler.codec.bytes.ByteArrayEncoder;
import io.netty.util.concurrent.DefaultEventExecutorGroup;
import io.netty.util.concurrent.EventExecutorGroup;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import java.nio.ByteOrder;

/**
 * 网状服务器
 *
 * @author youngki
 * @date 2022/10/20
 */
@Slf4j
@Component
public class NettyServer {


    @Autowired
    UserSmartIotByKeAnHandler userSmartIotByKeAnHandler;


    public static EventExecutorGroup defaultEventExecutor=new DefaultEventExecutorGroup(15);


    public String userDataByKeAn(Integer port) throws Exception {
        ServerBootstrap bootstrap = new ServerBootstrap();
        EventLoopGroup bossGroup = new NioEventLoopGroup();
        EventLoopGroup workerGroup = new NioEventLoopGroup();
        try {
            bootstrap.group(bossGroup, workerGroup);
            bootstrap.channel(NioServerSocketChannel.class);
            bootstrap.childHandler(new ChannelInitializer<SocketChannel>() {
                @Override
                public void initChannel(SocketChannel ch) throws Exception {

                    ch.pipeline().addLast("HexDecode",new LengthFieldBasedFrameDecoder(ByteOrder.LITTLE_ENDIAN,1024*50,24,2,4,0,false));
                    ch.pipeline().addLast("decode", new SmartByteToStringDecoder());
                    ch.pipeline().addLast("encode", new ByteArrayEncoder());
                    ch.pipeline().addLast(defaultEventExecutor,userSmartIotByKeAnHandler);
                }
            });
            bootstrap.option(ChannelOption.SO_BACKLOG, 1024 );
            bootstrap.option(ChannelOption.SO_RCVBUF,1024 );
            bootstrap.option(ChannelOption.SO_SNDBUF,1024 );
            bootstrap.childOption(ChannelOption.SO_KEEPALIVE, true);
            bootstrap.option(ChannelOption.TCP_NODELAY, true);

            ChannelFuture future = bootstrap.bind(port).sync();
            log.info("开始监听 用户信息传输装置"+ port);
            //启动一个线程 来给客户端发消息
            future.channel().closeFuture().sync();
        } catch (InterruptedException e) {
            e.printStackTrace();
        } finally {
            bossGroup.shutdownGracefully();
            workerGroup.shutdownGracefully();
        }

        return "msg:{成功}";
    }


}
